#include "TrHistoryQuote.h"

CTrHistoryQuote::CTrHistoryQuote(QObject *parent) : QObject(parent)
{

    m_pManager = new QNetworkAccessManager(this);
}

void CTrHistoryQuote::getDailyHistory(QString Instrument)
{
    Q_UNUSED(Instrument);
    QNetworkRequest request;

    QSslConfiguration config;
    QSslConfiguration conf = request.sslConfiguration();
    conf.setPeerVerifyMode(QSslSocket::VerifyNone);
    conf.setProtocol(QSsl::TlsV1SslV3);
    request.setSslConfiguration(conf);

    QString url;
    url = QString(SINA_FINANCE_URL_DAILY);
    url.replace("{:1}", Instrument);

    request.setUrl(QUrl(url));
    m_pDailyReply = m_pManager->get(request);

    connect(m_pDailyReply, SIGNAL(finished()), this, SLOT(OnDailyFinished()));
    connect(m_pDailyReply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(onError(QNetworkReply::NetworkError)));

}

void CTrHistoryQuote::getMiniHistory(QString Instrument)
{
    QNetworkRequest request;

    QSslConfiguration config;
    QSslConfiguration conf = request.sslConfiguration();
    conf.setPeerVerifyMode(QSslSocket::VerifyNone);
    conf.setProtocol(QSsl::TlsV1SslV3);
    request.setSslConfiguration(conf);

    QString url = QString("https://stock2.finance.sina.com.cn/futures/api/jsonp.php/TrManager/InnerFuturesNewService.getMinLine?symbol=").append(Instrument);

    request.setUrl(QUrl(url));
    m_pMiniReply = m_pManager->get(request);

    connect(m_pMiniReply, SIGNAL(finished()), this, SLOT(OnMiniFinished()));
    connect(m_pMiniReply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(onError(QNetworkReply::NetworkError)));
}

void CTrHistoryQuote::OnDailyFinished()
{

    QString codeContent = m_pDailyReply->readAll();
    qDebug() << __FUNCTION__ << codeContent.length();
    m_pTrImpl->OnResponse(Tr_ResponseID::TrOnDailyHistoryQuote, codeContent.toLatin1().data(), nullptr);
}

void CTrHistoryQuote::OnMiniFinished()
{
    QString codeContent = m_pMiniReply->readAll();
    codeContent.replace(");", "");
    codeContent.replace("/*<script>location.href='//sina.com';</script>*/\nTrManager(", "");
    m_pTrImpl->OnResponse(Tr_ResponseID::TrOnMiniHistoryQuote, codeContent.toLatin1().data(), nullptr);
}

void CTrHistoryQuote::onError(QNetworkReply::NetworkError e)
{
    qDebug() << __FUNCTION__ << e;
}

